package ajaxjs.data.service;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;

import ajaxjs.service.*;
public class BTest {
	private static B b = new B();
	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testMain() {
		//arrange
			Iterator i = mock(Iterator.class);
			when(i.next()).thenReturn("Hello").thenReturn("World");
			//act
			String result=i.next()+" "+i.next();
			//assert
			assertEquals("Hello World", result);
	}

	@Test
	public void testGetFoo() {
		assertEquals("Foo", b.getFoo());
	}

	class StubServletOutputStream extends ServletOutputStream {
		public ByteArrayOutputStream baos = new ByteArrayOutputStream();
		public void write(int i) throws IOException {
			baos.write(i);
		}
	}
	
	// http://blog.iprofs.nl/2011/03/03/how-we-do-unit-testing-with-junit-and-mockito/
	// http://blog.khubla.com/java/servlet-mocking-with-mockito
	
	@Test
	public void testBar() throws IOException, ServletException {
		BaseServlet bs = new BaseServlet();
		HttpServletRequest request = mock(HttpServletRequest.class);
		
		final ServletConfig servletConfig = mock(ServletConfig.class);
		when(servletConfig.getInitParameter("defaultPool")).thenReturn("testpool1");
		
		when(request.getPathInfo()).thenReturn("/lineup/world.xml");
		when(request.getParameter("a")).thenReturn("aaa");
		
		
		
		final HttpServletResponse response = mock(HttpServletResponse.class);
		final StubServletOutputStream servletOutputStream = new StubServletOutputStream();
		when(response.getOutputStream()).thenReturn(servletOutputStream);
		
		bs.init(servletConfig);
		bs.doPost(request, response);
		assertEquals("aaa", request.getParameter("a"));
	}
}
